﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Showroom.BLL;
using ShowroomMobile.Controls;

namespace ShowroomMobile
{
    public partial class ManagerCategory : AdminBasePage
    {
        View_Category cats;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ((AdminSite)Page.Master).SetTitlePage("Categories");
                LoadCategory();
            }
        }

        private void LoadCategory()
        {
            try
            {
                cats = View_Category.GetListCategory();
                cats.Filter = View_Category.ColumnNames.ParentID + " is NULL";
                for (int i = 0; i < cats.RowCount; i++)
                {
                    TreeNode node = new TreeNode(cats.s_Name, cats.s_ID);
                    node.PopulateOnDemand = true;

                    trvCategory.Nodes.Add(node);
                    cats.MoveNext();
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ManagerCategory.cs", "LoadCategory", ex.StackTrace);
            }
        }

        protected void trvCategory_TreeNodePopulate(Object sender, TreeNodeEventArgs e)
        {
            try
            {
                string catId = e.Node.Value;
                //select from topic where parentId = topicId.
                cats.Rewind();
                cats.Filter = View_Category.ColumnNames.ParentID + "=" + catId;
                for (int i = 0; i < cats.RowCount; i++)
                {
                    TreeNode node = new TreeNode(cats.s_Name, cats.s_ID);
                    node.PopulateOnDemand = true;

                    e.Node.ChildNodes.Add(node);
                    cats.MoveNext();
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ManagerCategory.cs", "trvCategory_TreeNodePopulate", ex.StackTrace);
            }
        }

        protected void btnRemove_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                int ID = Convert.ToInt32(trvCategory.SelectedNode.Value);
                Category.DeleteByID(ID);
                //Remove node
                if (trvCategory.SelectedNode.Parent != null)
                    trvCategory.SelectedNode.Parent.ChildNodes.Remove(trvCategory.SelectedNode);
                else
                    trvCategory.Nodes.Remove(trvCategory.SelectedNode);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ManagerCategory.cs", "btnRemove_Click", ex.StackTrace);
            }
        }

        protected void btnSaveCategory_Click(object sender, EventArgs e)
        {
            try
            {
                Showroom.BLL.Category cat = new Category();
                if (hidHandle.Value == "add")
                {
                    cat.AddNew();
                    cat.Name = txtCategoryName.Text.Trim();
                    if (trvCategory.SelectedNode != null)
                        cat.s_ParentID = (Convert.ToBoolean(hidIsChild.Value)) ? trvCategory.SelectedNode.Value : (trvCategory.SelectedNode.Parent != null) ? trvCategory.SelectedNode.Parent.Value : string.Empty;
                    else
                        cat.s_ParentID = string.Empty;
                    cat.Save();
                    //Add nodes
                    TreeNode node = new TreeNode(cat.s_Name, cat.s_ID);
                    if (trvCategory.SelectedNode != null)
                    {
                        if (Convert.ToBoolean(hidIsChild.Value))
                            trvCategory.SelectedNode.ChildNodes.Add(node);
                        else if (trvCategory.SelectedNode.Parent != null)
                            trvCategory.SelectedNode.Parent.ChildNodes.Add(node);
                        else
                            trvCategory.Nodes.Add(node);
                    }
                    else
                    {
                        trvCategory.Nodes.Add(node);
                    }
                    hidIsChild.Value = "false";
                }
                else
                {
                    cat.LoadByPrimaryKey(Convert.ToInt32(trvCategory.SelectedNode.Value));
                    cat.s_Name = txtCategoryName.Text.Trim();
                    cat.Save();
                    //Edit Node
                    hidCategoryName.Value = trvCategory.SelectedNode.Text = txtCategoryName.Text.Trim();
                    ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('Star Case', 'Invalid image!', 8000);", 1), true); 
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ManagerCategory.cs", "btnSaveCategory_Click", ex.StackTrace);
            }
        }

        protected void trvCategory_SelectedNodeChanged(object sender, EventArgs e)
        {
            //ckbIsChild.Enabled = true;
            hidCategoryName.Value = trvCategory.SelectedNode.Text;

            gridCurrentProducts.Rebind();

            hidUrlAddProduct.Value = string.Format(Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath + "AddProduct.aspx?cid={0}", trvCategory.SelectedNode.Value);
            lnkNewProduct.NavigateUrl = "~/UpdateProduct.aspx?ReturnURL=ManagerCategory.aspx&CateID=" + trvCategory.SelectedNode.Value;
        }

        protected void gridCurrentProducts_OnNeedDataSource(object sender, EventArgs e)
        {
            View_CategoryProducts cProds = new View_CategoryProducts();
            string sFilter = string.Format("{0} = {1}", View_CategoryProducts.ColumnNames.CategoryID, (trvCategory.SelectedNode != null)? trvCategory.SelectedNode.Value : "0123456789");
            int total = cProds.Search(sFilter, "[ID] desc", gridCurrentProducts.CurrentPageIndex * gridCurrentProducts.PageSize, gridCurrentProducts.PageSize);
            gridCurrentProducts.VirtualItemCount = total;
            gridCurrentProducts.DataSource = cProds.DefaultView;
            
        }

        protected void gridCurrentProducts_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            gridCurrentProducts.CurrentPageIndex = e.NewPageIndex;
            gridCurrentProducts.Rebind();
        }

        protected void gridCurrentProducts_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "DeleteAll")
            {
                //Delete all
                CategoryProduct.DeleteAllProducts(Convert.ToInt32(trvCategory.SelectedNode.Value));
                gridCurrentProducts.CurrentPageIndex = 0;
                gridCurrentProducts.Rebind();
            }
            else if (e.CommandName == "Delete")
            {
                int ID = Convert.ToInt32(e.CommandArgument);
                CategoryProduct.DeleteProductByID(ID);
                gridCurrentProducts.CurrentPageIndex = 0;
                gridCurrentProducts.Rebind();
            }
        }

        protected void btnReloadGridCurrentProducts_Click(object sender, EventArgs e)
        {
            try
            {
                gridCurrentProducts.CurrentPageIndex = 0;
                gridCurrentProducts.Rebind();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ManagerCategory.cs", "btnReloadGridCurrentProducts_Click", ex.StackTrace);
            }
        }
    }
}